import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:schedule_self_client/api/tool/tool_api.dart';
import 'package:schedule_self_client/api/user_center/login_resp.dart';
import 'package:schedule_self_client/api/user_center/user_api.dart';
import 'package:schedule_self_client/api/user_center/user_info_qry_resp.dart';
import 'package:schedule_self_client/state_management/providers/login_status.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Padding(
      padding: const EdgeInsets.all(16.0),
      child: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextFormField(
              controller: _usernameController,
              decoration: const InputDecoration(
                icon: Icon(Icons.person),
                hintText: '请输入用户名',
                labelText: '用户名',
              ),
              validator: (String? value) {
                if (value == null || value.isEmpty) {
                  return '用户名不能为空';
                }
                return null;
              },
            ),
            const SizedBox(
              height: 16,
            ),
            TextFormField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                icon: Icon(Icons.password),
                hintText: '请输入密码',
                labelText: '密码',
              ),
              validator: (String? value) {
                if (value == null || value.isEmpty) {
                  return '密码不能为空';
                }
                return null;
              },
            ),
            const SizedBox(
              height: 48,
            ),
            TextButton(
                onPressed: () {
                  ToolApi().downloadApp(
                      'https://scheduleself.smallwang.ltd:9004/temp/app.apk',
                      'app.apk',
                      context);
                  GoRouter.of(context).push('/download_loading_page');
                },
                child: Text('临时测试下载')),
            const SizedBox(
              height: 48,
            ),
            ElevatedButton(
                onPressed: () {
                  bool isValid = _formKey.currentState!.validate();
                  if (isValid) {
                    final username = _usernameController.value.text;
                    final password = _passwordController.value.text;
                    _login(context, username, password);
                  }
                },
                style: ElevatedButton.styleFrom(
                    backgroundColor: Theme.of(context).primaryColor),
                child: const Text(
                  '登录',
                  style: TextStyle(color: Colors.white),
                )),
          ],
        ),
      ),
    ));
  }

  _login(BuildContext context, String username, String password) async {
    LoginResp? loginResp = await UserApi.login(username, password, 123456);
    if (loginResp == null) {
      return;
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('user_token', loginResp.data.tokenValue);
    UserInfoQryResp? userInfoQryResp = await UserApi.queryUserInfo();
    Provider.of<LoginInfo>(context, listen: false)
        .login(loginResp, userInfoQryResp);
  }
}
